var express = require('express');
var WXPay = require('node-wxpay');
var fs = require('fs');
var router = express.Router();

var wxpay = WXPay({
    appid: '公众号ID',
    mch_id: '商户号ID',
    partner_key: '商户密钥（证书密码）',
    pfx: fs.readFileSync('./证书路径.p12'),
});


router.get('/', function (req, res, next) {
    res.render('index', {title: 'Express'});
});

/**
 * 创建扫码支付订单（统一下单接口）
 */
router.get('/createOrder', function (req, res, next) {
    wxpay.createUnifiedOrder({
        body: '扫码支付测试',
        out_trade_no: 'API2019010100001003',
        //+ Math.random().toString().substr(2, 10)
        total_fee: 1,
        spbill_create_ip: '192.168.2.210',
        notify_url: 'http://mp.ngrok.xiaomiqiu.cn/Receive/WxReceive',
        trade_type: 'NATIVE',
        product_id: '1234567890'
    }, function (err, result) {
        console.log(result);
    });
    res.send('respond with a resource');
});

/**
 * 通过商户订单号查
 */
router.get('/queryOrder', function (req, res, next) {
    wxpay.queryOrder({ out_trade_no:"API2019010100001003" }, function(err, order){
        console.log(order);
    });
    res.send('respond with a resource');
});

/**
 * 关闭订单
 */
router.get('/closeOrder', function (req, res, next) {
    wxpay.closeOrder({ out_trade_no:"API2019010100001003"}, function(err, result){
        console.log(result);
    });
    res.send('respond with a resource');
});

/**
 * 订单退款
 */
router.get('/refundOrder', function (req, res, next) {
    wxpay.refundOrder({
        out_trade_no: 'API2019010100001003',
        total_fee: 1,
        refund_fee: 1,
        notify_url: 'http://mp.ngrok.xiaomiqiu.cn/Receive/WxRefund',
        out_refund_no: 'RFD2019010100001002'
    }, function(err, result){
        console.log(result);
    });
    res.send('respond with a resource');
});


module.exports = router;
